﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utils.Common;
using Utils.Common.Enum;
using ZK.BLL;
using ZK.BLL.Config;
using ZK.BLL.MainExecute;
using ZK.Entity;
using ZK.MyControl;
using static Utils.Common.LogHelper;

namespace ZK.Client.WinForm
{
    public partial class FrmMainExecute : Form
    {
        public FrmMainExecute()
        {
            InitializeComponent();
            LogHelper.LogEventHandler += LogEventHandler;
            FrmPrintData.SelectedEvent += FrmPrintData_SelectedEvent;
        }
 
        private void LogEventHandler(object sender, EventArgs e)
        {
            LogEntity logEntity = (LogEntity)sender;
            switch (logEntity.LogEnum)
            {
                case LogEnum.Info: { richTextBoxPanel1.LogMessage(logEntity.Message); break; }
                case LogEnum.Debug: { richTextBoxPanel1.LogWarning(logEntity.Message); break; }
                case LogEnum.Error: { richTextBoxPanel1.LogError(logEntity.Message); break; }
            }
        }


        public string currCustomer = string.Empty;
        public string currProductName = string.Empty;



        private void GetCurrent()
        {
            currCustomer = cmbCustomer.Text.Trim();
            currProductName = cmbProductName.Text.Trim();
            //txtDate.Text = CalculateDate.GetDate();
        }
        private void FrmMainExecute_Load(object sender, EventArgs e)
        {
 
            //string logofile = ConfigBase.LogoImg + "\\" + TempConfig.GetConfig().LogoName;
            //if (File.Exists(logofile))
            //{
            //    pbLogo.Image = Image.FromFile(logofile);
            //    pbLogo.Tag = Path.GetFileName(logofile);
            //}
            btnDoPrint.Enabled = false;


            cmbCustomer.SelectedIndexChanged += CmbCustomer_SelectedIndexChanged;
            var list = ProductInfoBLL.Instance.GetList();
            if (list!=null&&list.Count > 0)
            {
                string[] customers = ProductInfoBLL.Instance.GetList().Select(s => s.CustomerName).Distinct().ToArray();
                cmbCustomer.DataSource = customers;

                if (customers.Length > 0)
                {
                    cmbCustomer.SelectedIndex = 0;
                }

            }
            FrmProductInfo.SaveEvent += saveEvent;

            if (TempConfig.GetConfig().CustomerName != null)
            {
                cmbCustomer.SelectedIndex = cmbCustomer.FindString(TempConfig.GetConfig().CustomerName);
            }
            if (TempConfig.GetConfig().ProductName != null)
            {
                cmbProductName.SelectedIndex = cmbProductName.FindString(TempConfig.GetConfig().ProductName);
            }
            if (TempConfig.GetConfig().BatchNo != null)
            {
                txtBatchNo.Text = TempConfig.GetConfig().BatchNo;
            }
            if (TempConfig.GetConfig().ModelNo != null)
            {
                txtModelNo.Text = TempConfig.GetConfig().ModelNo;
            }

            if ( TempConfig.GetConfig().PatentNo!=null)
            {
                txtPatentNO.Text = TempConfig.GetConfig().PatentNo;
            }
        }

        private void FrmPrintData_SelectedEvent(string id)
        {
            var printData = PrintDataBLL.Instance.Get(id);
            if (printData != null)
            {
                cmbCustomer.SelectedIndex = cmbCustomer.FindString(printData.CustomerName);
                cmbProductName.SelectedIndex = cmbProductName.FindString(printData.ProductName);
                txtModelNo.Text = printData.ModelNo;
                txtBatchNo.Text = printData.BatchNo;
                //txtDate.Text = CalculateDate.GetDate();
            }
        }
        private void CmbCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            string customer = cmbCustomer.Text.Trim();

            string imgFilePath = ConfigBase.LogoImg + "\\" + customer + ".bmp";
            if (File.Exists(imgFilePath))
            {
                Image img = Image.FromFile(imgFilePath);
                Bitmap imgNew = new Bitmap(img);
                img.Dispose();
                if (pbLogo.Image != null)
                {
                    pbLogo.Image.Dispose();
                }
                pbLogo.Image = imgNew;
            }





            var productInfoList= ProductInfoBLL.Instance.GetList().FindAll(s => s.CustomerName == customer);
            cmbProductName.DataSource = productInfoList;
            cmbProductName.DisplayMember = nameof(ProductInfo.ProductName);
            cmbProductName.ValueMember = nameof(ProductInfo.Id);

            if (productInfoList != null&& productInfoList.Count>0)
            {
                cmbProductName.SelectedIndex = 0;
            }
            GetCurrent();
        }

        private void cmbProductName_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetCurrent();

            var productInfo = (ProductInfo)cmbProductName.SelectedItem;

            string imgFilePath;
            if (!string.IsNullOrEmpty(productInfo.CustomerName2))
            {
                imgFilePath = ConfigBase.LogoImg + "\\" + productInfo.CustomerName2 + ".bmp";
            }
            else
            {
                imgFilePath = ConfigBase.LogoImg + "\\Empty.bmp";
            }

            if (File.Exists(imgFilePath))
            {
                Image img = Image.FromFile(imgFilePath);
                Bitmap imgNew = new Bitmap(img);
                img.Dispose();
                if (pbLogo2.Image != null)
                {
                    pbLogo2.Image.Dispose();
                }
                pbLogo2.Image = imgNew;
            }


        }

        private void saveEvent(object sender, EventArgs e)
        {

            string customer = currCustomer;
            string productName = currProductName;

            string[] customers = ProductInfoBLL.Instance.GetList().Select(s => s.CustomerName).Distinct().ToArray();
            cmbCustomer.DataSource = customers;

            cmbCustomer.SelectedIndex = cmbCustomer.FindString(customer);
            cmbProductName.SelectedIndex = cmbProductName.FindString(productName);
        }

        private void btnOpt_Click(object sender, EventArgs e)
        {

            if (PrinterSettingConfig.GetConfig().PrinterSettingList == null || PrinterSettingConfig.GetConfig().PrinterSettingList.Count == 0)
            {
                MessageBox.Show("请先设置喷码机通讯地址！");
                return;

            }
  
            
             string productName = cmbProductName.Text.Trim();
     
            if (cmbCustomer.SelectedIndex < 0) return;

 


            if (btnOpt.Text == "连接")
            {
                 
                richTextBoxPanel1.TxtClear();

                var printerSetting = PrinterSettingConfig.GetConfig().PrinterSettingList.First() ;

                 GlobalExecute.Instance.Start(cmbCustomer.Text.Trim(), productName, printerSetting.IPAddress, printerSetting.Port);
                if (GlobalExecute.Instance.IsRunning)
                {
                    btnOpt.Text = "断开";
                 
               
                    btnDoPrint.Enabled = true;

                    LogHelper.LogInfo("连接成功");
                    //DoPrint(GlobalExecute.Instance.GetNewPrintData());

                }
               
            }
            else
            {
                GlobalExecute.Instance.Stop();
                if (!GlobalExecute.Instance.IsRunning)
                {

                    btnOpt.Text = "连接";
           
             
                    btnDoPrint.Enabled = false;
                    LogHelper.LogInfo("连接已断开");

                }
            }

           
        }


       

      

        //private void pbLogo_Click(object sender, EventArgs e)
        //{
        //    using (OpenFileDialog ofd = new OpenFileDialog())
        //    {
        //        ofd.InitialDirectory = ConfigBase.LogoImg;
        //        ofd.Filter = "(图片)*.bmp|*.bmp";
        //        if (ofd.ShowDialog() == DialogResult.OK)
        //        {
        //            pbLogo.Image = Image.FromFile(ofd.FileName);
        //            pbLogo.Tag = Path.GetFileName(ofd.FileName);
        //        }
        //    }
        //}

      

        public void PanelAddControl(string imgName,string imgName2,string productName,string sno,string other)
        {
            panelPrinter.Controls.Clear();
            int height = 20;
            int currX = 20;

            Image image = Bitmap.FromFile(ConfigBase.LogoImg + "\\" + imgName+".bmp");
            PictureBox pb1 = new PictureBox();
            pb1.Image = image;
            pb1.SizeMode = PictureBoxSizeMode.Zoom;
            pb1.Size = new Size(100, 30);
            pb1.Location = new Point(currX, height);
            panelPrinter.Controls.Add(pb1);
            currX += pb1.Width;

            if (!string.IsNullOrEmpty(imgName2))
            {
                Image image2 = Bitmap.FromFile(ConfigBase.LogoImg + "\\" + imgName2 + ".bmp");
                PictureBox pb2 = new PictureBox();
                pb2.Image = image2;
                pb2.SizeMode = PictureBoxSizeMode.Zoom;
                pb2.Size = new Size(100, 30);
                pb2.Location = new Point(currX, height);
                panelPrinter.Controls.Add(pb2);
                currX += pb2.Width;
            }
            else
            {
                Image image2 = Bitmap.FromFile(ConfigBase.LogoImg + "\\Empty.bmp");
                PictureBox pb2 = new PictureBox();
                pb2.Image = image2;
                pb2.SizeMode = PictureBoxSizeMode.Zoom;
                pb2.Size = new Size(100, 30);
                pb2.Location = new Point(currX, height);
                panelPrinter.Controls.Add(pb2);
                currX += pb2.Width;
            }
                
            Label lbl1 = new Label();
            lbl1.AutoSize = true;
            lbl1.Font = panelPrinter.Font;
            lbl1.Location = new Point(currX, height);
            lbl1.Text = productName;
            panelPrinter.Controls.Add(lbl1);
            currX += lbl1.Width;
 
            Label lbl2 = new Label();
            lbl2.AutoSize = true;
            lbl2.Font = panelPrinter.Font;
            lbl2.Location = new Point(currX, height);
            lbl2.Text = sno;
            panelPrinter.Controls.Add(lbl2);
            currX += lbl2.Width;

            Label lbl3 = new Label();
            lbl3.AutoSize = true;
            lbl3.Font = panelPrinter.Font;
            lbl3.Location = new Point(currX, height);
            lbl3.Text = other;
            panelPrinter.Controls.Add(lbl3);
            currX += lbl3.Width;

        }



        private void btnDoPrint_Click(object sender, EventArgs e)
        {


            if (string.IsNullOrEmpty(txtModelNo.Text))
            {

                LogHelper.LogError("请先输入型号号！");
                return;
            }


            string batch = txtBatchNo.Text.Trim();
            if (string.IsNullOrEmpty(batch))
            {

                LogHelper.LogError("请先输入编码！");
                return;
            }

            if (cmbProductName.SelectedIndex==-1)
            {

                LogHelper.LogError("请先选择系列！");
                return;
            }

            var printerSetting = PrinterSettingConfig.GetConfig().PrinterSettingList.First();

            var productInfo  =(ProductInfo) cmbProductName.SelectedItem;
            PrintData printData = new PrintData();
            printData.Id = PrintDataBLL.Instance.GetNewID();
            printData.PrinterName = printerSetting.PrinterName;
            printData.CustomerName = cmbCustomer.Text.Trim();
            printData.CustomerName2 = productInfo.CustomerName2;
            printData.ProductName = productInfo.ProductName;
            printData.ModelNo = txtModelNo.Text;
            printData.BatchNo = txtBatchNo.Text;
            printData.UserPrintName = Class_Config.UserInfo.PrintName;
            printData.Other = productInfo.Other;
            printData.PatentNO = txtPatentNO.Text.Trim();
            //if (cbDate.Checked)
            //{
            //    printData.BatchNo += txtDate.Text.Trim();
            //}

            printData.PersonName = Class_Config.UserInfo.PersonName;
            printData.TemplateName = productInfo.TemplateName;
            printData.PrintDate = DateTime.Now;
            DoPrint(printData);

            try
            {
                TempConfig.GetConfig().CustomerName = cmbCustomer.Text.Trim();
                TempConfig.GetConfig().ProductName = cmbProductName.Text.Trim();
                TempConfig.GetConfig().ModelNo = txtModelNo.Text;
                TempConfig.GetConfig().BatchNo = txtBatchNo.Text.Trim();
                TempConfig.GetConfig().PatentNo = txtPatentNO.Text.Trim();
                TempConfig.GetConfig().EditConfig();

            }
            catch { }
        }


        private void DoPrint( PrintData printData)
        {
            if (!GlobalExecute.Instance.IsRunning) return;
       
           
            PanelAddControl(printData.CustomerName, printData.CustomerName2, printData.ProductName+ printData.ModelNo, printData.PatentNO+" "+  printData.UserPrintName+printData.BatchNo,printData.Other);

            GlobalExecute.Instance.ReSend(printData);
        }

        private void btnSet_Click(object sender, EventArgs e)
        {


            //bool result = GlobalExecute.Instance.UpdateVDJParam(cmbFlipIndex.SelectedIndex, cmbOverthrow.SelectedIndex, uc_Width.Value, uc_Height.Value, uc_CharacterGap.Value, uc_Delay.Value, cmbFontHigh.Text);
            //if (result)
            //{
            //    VDJSetConfig.GetConfig().FlipIndex = cmbFlipIndex.SelectedIndex;
            //    VDJSetConfig.GetConfig().OverthrowIndex = cmbOverthrow.SelectedIndex;
            //    VDJSetConfig.GetConfig().Width = uc_Width.Value;
            //    VDJSetConfig.GetConfig().Height = uc_Height.Value;
            //    VDJSetConfig.GetConfig().CharacterGap = uc_CharacterGap.Value;
            //    VDJSetConfig.GetConfig().Delay = uc_Delay.Value;
            //    VDJSetConfig.GetConfig().FontHigh = cmbFontHigh.Text;
            //    VDJSetConfig.GetConfig().EditConfig();

            //}
            //else
            //{pbLogo
            //    MessageBox.Show("设置失败");
            //}
        }

        private void pbLogo_Click(object sender, EventArgs e)
        {
            FrmCustomerSelect frm = new FrmCustomerSelect();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                cmbCustomer.SelectedIndex = cmbCustomer.FindString(frm.Selected);
            }
        }

  
    }
}
